<?php


namespace support\command\workerman\event;

use app\common\gateway\data\ClientSender;
use app\common\gateway\data\JsonData;
use GatewayWorker\Lib\Gateway;
use support\command\workerman\GatewayWorker;
use Workerman\Lib\Timer;

class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        $sender = new ClientSender($client_id);
        $sender->send(new JsonData('get_client_id', [
            'client_id' => $client_id
        ]));
        // 启动关闭未认证链接
        self::closeNoAuthClient($client_id);
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        $message = json_decode($message, true);
        switch($message['type'])
        {
            case 'login':
                $token = md5(md5($client_id) . GatewayWorker::TOKEN_KEY);
                if ($message['data']['token'] == $token) {
                    $session = Gateway::getSession($client_id);
                    Timer::del($session['auth_timer_id']);
                }
                break;
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {

    }

    protected static function closeNoAuthClient($client_id) {
        // 当30秒都没有认证 关闭链接
        $auth_timer_id = Timer::add(30, function($client_id){
            $data = new JsonData('alert_msg', [
                'code' => 0,
                'msg' => '验证失败'
            ]);
            $sender = new ClientSender($client_id);
            $sender->send($data);
            Gateway::closeClient($client_id);
        }, [$client_id], false);
        Gateway::updateSession($client_id, ['auth_timer_id' => $auth_timer_id]);
    }
}
